package com.jn.erp.web.api.sys.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jn.erp.security.entity.SysPermission;
import com.jn.erp.security.entity.SysRole;
import com.jn.erp.web.api.sys.entity.SysRolePermission;
import com.jn.erp.web.api.sys.mapper.SysRolePermissionMapper;
import com.jn.erp.web.api.sys.service.SysRolePermissionService;
import com.jn.erp.web.result.TreeSelect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;


/**
 * <pre>
 *
 * </pre>
 *
 * @author sunjiyong
 * @since 2024/8/28 15:45
 */
@Service
public class SysRolePermissionServiceImpl extends ServiceImpl<SysRolePermissionMapper, SysRolePermission> implements SysRolePermissionService {
    @Autowired
    private com.jn.erp.security.sysservice.SysPermissionService sysPermissionService;
    /**
     * 构建前端所需要下拉树结构
     *
     * @param menus 菜单列表
     * @return 下拉树结构列表
     */
    @Override

    public List<TreeSelect> buildMenuTreeSelect(List<SysPermission> menus) {
        List<SysPermission> menuTrees = buildMenuTree(menus);
        return menuTrees.stream().map(TreeSelect::new).collect(Collectors.toList());
    }

    /**
     * 新增角色菜单信息
     *
     * @param role 角色对象
     */
    public boolean insertRoleMenu(SysRole role) {
        boolean rows = false;
        // 新增用户与角色管理
        List<SysRolePermission> list = new ArrayList<SysRolePermission>();
        for (Long menuId : role.getMenuIds()) {
            SysRolePermission rm = new SysRolePermission();
            rm.setRoleId(role.getRoleId());
            rm.setMenuId(menuId);
            list.add(rm);
        }
        if (list.size() > 0) {
            rows = this.saveBatch(list);
        }
        return rows;
    }


    /**
     * 构建前端所需要树结构
     *
     * @param menus 菜单列表
     * @return 树结构列表
     */
    public List<SysPermission> buildMenuTree(List<SysPermission> menus) {
        List<SysPermission> returnList = new ArrayList<SysPermission>();
        List<Long> tempList = menus.stream().map(SysPermission::getMenuId).collect(Collectors.toList());
        for (Iterator<SysPermission> iterator = menus.iterator(); iterator.hasNext(); ) {
            SysPermission menu = (SysPermission) iterator.next();
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(menu.getParentId())) {
                sysPermissionService.recursionFn(menus, menu);
                returnList.add(menu);
            }
        }
        if (returnList.isEmpty()) {
            returnList = menus;
        }
        return returnList;
    }
}
